import os
import json
import shutil
from pathlib import Path
from typing import Optional, Union, Dict, List

class FileUtils:
    """文件操作工具类，处理所有文件相关的操作"""
    
    @staticmethod
    def ensure_dir_exists(dir_path: Union[str, Path]) -> bool:
        """确保目录存在，不存在则创建"""
        try:
            Path(dir_path).mkdir(parents=True, exist_ok=True)
            return True
        except (OSError, PermissionError) as e:
            print(f"创建目录失败: {e}")
            return False
    
    @staticmethod
    def read_json(file_path: Union[str, Path]) -> Optional[Union[Dict, List]]:
        """读取JSON文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"读取JSON文件失败: {e}")
            return None
    
    @staticmethod
    def write_json(file_path: Union[str, Path], data: Union[Dict, List]) -> bool:
        """写入JSON文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=4, ensure_ascii=False)
            return True
        except (OSError, TypeError) as e:
            print(f"写入JSON文件失败: {e}")
            return False
    
    @staticmethod
    def copy_file(src: Union[str, Path], dst: Union[str, Path]) -> bool:
        """复制文件"""
        try:
            shutil.copy2(src, dst)
            return True
        except (FileNotFoundError, PermissionError) as e:
            print(f"复制文件失败: {e}")
            return False
    
    @staticmethod
    def remove_file(file_path: Union[str, Path]) -> bool:
        """删除文件"""
        try:
            Path(file_path).unlink(missing_ok=True)
            return True
        except (OSError, PermissionError) as e:
            print(f"删除文件失败: {e}")
            return False
    
    @staticmethod
    def get_file_size(file_path: Union[str, Path]) -> Optional[int]:
        """获取文件大小(字节)"""
        try:
            return os.path.getsize(file_path)
        except (FileNotFoundError, OSError) as e:
            print(f"获取文件大小失败: {e}")
            return None
    
    @staticmethod
    def find_files_by_ext(directory: Union[str, Path], extension: str) -> List[str]:
        """查找指定扩展名的文件"""
        try:
            return [str(f) for f in Path(directory).glob(f'*.{extension}')]
        except OSError as e:
            print(f"查找文件失败: {e}")
            return []
    
    @staticmethod
    def get_cover_path(cover_dir: Union[str, Path], station_id: str) -> Path:
        """获取电台封面路径"""
        cover_dir = Path(cover_dir)
        # 尝试多种可能的图片格式
        for ext in ['png', 'jpg', 'jpeg', 'gif']:
            cover_path = cover_dir / f"{station_id}.{ext}"
            if cover_path.exists():
                return cover_path
        # 返回默认封面路径
        return cover_dir / "default.png"
    
    @staticmethod
    def is_hidden(file_path: Union[str, Path]) -> bool:
        """检查文件/目录是否为隐藏"""
        name = Path(file_path).name
        return name.startswith('.')